import { desktopCapturer, ipcMain, IpcMainEvent } from "electron";
import { createWindow, getSize, getTargetWindow } from "../window/CreateWindow";

export function cutImageEvent() {
  // 截图方式
  let cutImageType: "window" | "screen" | null = null;
  // 截图
  ipcMain.on("open_screen_shot", (_event: IpcMainEvent, type: "window" | "screen") => {
    cutImageType = type;
    let cutWindow = getTargetWindow("screenshot");
    if (cutWindow) {
      cutWindow.close();
      cutWindow = null;
    }
    let { width, height } = getSize();
    getTargetWindow("home")?.hide();
    createWindow("screenshot", width, height, "screenshot");
  });

  ipcMain.on("show_screen_shot", async () => {
    let cutWindow = getTargetWindow("screenshot");
    let sources = await desktopCapturer.getSources({
      types: [cutImageType ? cutImageType : "window"],
      thumbnailSize: getSize(),
    });
    cutWindow?.webContents.send("get_screen_source", sources[0].thumbnail.toDataURL());
  });

  ipcMain.on("confirm_screen_shot", (_event: IpcMainEvent, data: string) => {
    getTargetWindow("home")?.webContents.send("cut_screen_result", data);
    getTargetWindow("screenshot")?.close();
    getTargetWindow("home")?.show();
  });

  ipcMain.on("close_screen_shot", () => {
    getTargetWindow("screenshot")?.close();
    getTargetWindow("home")?.show();
  });
}
